package controller

import (
	"fmt"
	"gin/common"
	"gin/response"
	"gin/util"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"strconv"
)

type Shop struct {
	ShopId          int     `gorm:"column:id"`
	ShopName        string  `gorm:"column:name"`
	SelfMention     int     `gorm:"column:openZiqu"`
	SendToDoor      int     `gorm:"column:openWaimai"`
	SendDistance    float64 `gorm:"column:sendDistance"`
	Status          string  `gorm:"column:status"`
	LinkPhone       string  `gorm:"column:linkPhone"`
	Latitude        float64 `gorm:"column:latitude"`
	Longitude       float64 `gorm:"column:longitude"`
	Address         string  `gorm:"column:address"`
	Pic             string  `gorm:"column:pic"`
	SendMoney       float64 `gorm:"column:sendMoney"`
	PeisongType     string  `gorm:"column:peisongType"`
	AmountLogistics string  `gorm:"column:amountLogistics"`
	OpeningHours    string  `gorm:"column:openingHours"`
	Distance        string
}

func ShopList(ctx *gin.Context) {
	var shopList []Shop
	db := common.GetDB()
	db.Table("cat_meal_shop").Where("status !=-1").Find(&shopList)
	rdb := common.GetRedis()
	lat := ctx.PostForm("lat")
	lng := ctx.PostForm("lng")
	newLat, _ := strconv.ParseFloat(lat, 64) //64位转字符串
	newlng, _ := strconv.ParseFloat(lng, 64)
	ip := util.GetLocalIP()
	res, err := rdb.GeoAdd("shopList", &redis.GeoLocation{
		Name:      ip,
		Longitude: newlng,
		Latitude:  newLat,
	}).Result()
	if err != nil {
		fmt.Printf(" err:%v\n res:%v\n", err, res)
		return
	}
	var shopList2 []Shop

	for _, item := range shopList {
		shopIdStr := strconv.Itoa(item.ShopId)
		resPos, _ := rdb.GeoPos("shopList", "shop_"+shopIdStr).Result()
		if resPos[0] == nil {
			res, _ := rdb.GeoAdd("shopList", &redis.GeoLocation{
				Name:      "shop_" + shopIdStr,
				Longitude: item.Longitude,
				Latitude:  item.Latitude,
			}).Result()
			fmt.Println(res)
		}
		resDist, _ := rdb.GeoDist("shopList", ip, "shop_"+shopIdStr, "m").Result()
		item.Distance = util.ShowDistance(resDist)
		shopList2 = append(shopList2, item)
	}
	response.Success(ctx, gin.H{"shopList": shopList2}, "success")
}
